package com.project.school_flate.serviceimpl.flow;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;
import com.project.school_flate.entity.com.ComDistributionRule;
import com.project.school_flate.entity.com.table.ComDistributionRuleTableDef;
import com.project.school_flate.entity.delivery.DeliveryInfo;
import com.project.school_flate.entity.flow.FlowTask;
import com.project.school_flate.entity.flow.table.FlowTaskTableDef;
import com.project.school_flate.entity.shop.ShopInfo;
import com.project.school_flate.entity.user.UserInfo;
import com.project.school_flate.mapper.com.ComDistributionRuleMapper;
import com.project.school_flate.mapper.flow.FlowTaskMapper;
import com.project.school_flate.mapper.user.UserInfoMapper;
import com.project.school_flate.service.flow.FlowTaskService;
import com.project.school_flate.util.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(value = "flowTaskServiceImpl")
public class FlowTaskServiceImpl implements FlowTaskService {

    @Autowired
    private FlowTaskMapper oFlowTaskMapper;

    @Autowired
    private UserInfoMapper oUserInfoMapper;

    @Autowired
    private ComDistributionRuleMapper oComDistributionRuleMapper;

    /**
     * 执行任务，把金额发向各个角色
     * 定时任务，间隔:每天2时执行一次
     *
     */
    @Override
    @Transactional
    public void executeFlowTask() throws Exception {
        //获取昨天的开始时间和结束时间
        Map<String, Date> timeMap = DateUtils.getYesterdayTime();
        //获取所有未完成的任务
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(FlowTaskTableDef.FLOW_TASK.STATE.eq(0));
        queryWrapper.where(FlowTaskTableDef.FLOW_TASK.CREATE_TIME.between(timeMap.get("startTime"),timeMap.get("endTime")));
        List<FlowTask> oFlowTaskList = oFlowTaskMapper.selectListByQuery(queryWrapper);
        for(FlowTask oFlowTask : oFlowTaskList){
            if(StringUtils.isNotBlank(oFlowTask.getUserId())){
                UserInfo oUserInfo = oUserInfoMapper.selectOneById(oFlowTask.getUserId());
                oUserInfo.setDistributionPrice(oUserInfo.getDistributionPrice() + oFlowTask.getMoney());
                oUserInfo.setBalance(oUserInfo.getBalance() + oFlowTask.getMoney());
                //判断用户是否是专业分销商
                if(oUserInfo.getIsDistribution() == 1){
                    //获取所有的分销商等级规则
                    queryWrapper = new QueryWrapper();
                    queryWrapper.where(ComDistributionRuleTableDef.COM_DISTRIBUTION_RULE.TYPE.eq(oUserInfo.getIsDistribution()));
                    queryWrapper.where(ComDistributionRuleTableDef.COM_DISTRIBUTION_RULE.INCOME.ge(oUserInfo.getDistributionPrice()));
                    queryWrapper.orderBy("income asc");
                    queryWrapper.limit(1);
                    ComDistributionRule oComDistributionRule = oComDistributionRuleMapper.selectOneByQuery(queryWrapper);
                    if(oComDistributionRule != null && oComDistributionRule.getGrade().compareTo(oUserInfo.getDistributionGrade()) > 0){
                        oUserInfo.setDistributionGrade(oComDistributionRule.getGrade());
                    }
                }
                oUserInfoMapper.update(oUserInfo);
            }else if(StringUtils.isNotBlank(oFlowTask.getShopId())){
                UpdateChain.of(ShopInfo.class)
                        .setRaw(ShopInfo::getBalance, "balance + " + oFlowTask.getMoney())
                        .where(ShopInfo::getId).eq(oFlowTask.getShopId())
                        .update();
            }else if(StringUtils.isNotBlank(oFlowTask.getDeliveryId())){
                UpdateChain.of(DeliveryInfo.class)
                        .setRaw(DeliveryInfo::getIncome, "income + " + oFlowTask.getMoney())
                        .setRaw(DeliveryInfo::getBalance, "balance + " + oFlowTask.getMoney())
                        .where(DeliveryInfo::getId).eq(oFlowTask.getDeliveryId())
                        .update();
            }
        }
    }

}
